--
-- Author: bin.zhao
-- Date: 2018-06-15 11:31:42
--
-- JewelController
--

local Jewel = require("app.public.dao.Jewel")
local JewelView = import("..views.JewelView")
local JewelStarView = import("..views.JewelStarView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
    self.super.ctor(self, params)
end

function ClassRef:init()
	cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()
    self._model = app:getInst("JewelModel")

    self.panelIdx = 1
    
    self._bagHandler = UD.bag:onChanged(handler(self, self.updateBag))
    self._walletHandler = UD:onChanged("wallet", handler(self, self.updateWallet))
end
--宝石合成后 现实已合成的宝石
function ClassRef:updateBag(uid, item, amountGot, opt)
    if cc.isDead(self._view) then return end

    if opt == "update" then

    elseif opt == "insert" then
        if self._view and item.itemBagType == Enums.ItemBagType.jewel then
            self._view:refreshComposeResult(item,3,true)

             if self.panelIdx == 3 then
                self.transformJewelUid = uid
            end
        end
    end

    -- 宝石炼金所需，则刷新界面
    if self._curTransformJewel and
        self.panelIdx == 3 and
        self._curTransformJewel:isTransformCostItem(item:getId()) then

        local transfromPanel = self._view:getTransformPanel()
        transfromPanel:updateCostItems()
    end
end

function ClassRef:updateWallet(name, old, new)
    if cc.isDead(self._view) then return end

    if name == "gold" or name == "magicDust" then
        if self.panelIdx == 3 then
            local transfromPanel = self._view:getTransformPanel()
            transfromPanel:refreshResNum()
        end
    end
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)

    UD.bag:unChanged(self._bagHandler)
    UD:unChanged("wallet", self._walletHandler)
end

function ClassRef:listEvent()
    return {
        "EVENT_HIDE_JEWEL_VIEW",
        "EVENT_EQUIP_JEWEL",
        "EVENT_UNEQUIP_JEWEL",
        "EVENT_REFRESH_BAG",
        "EVENT_REFRESH_UPGRADE",
        "EVENT_REFRESH_UPGRADEBAG",
        "EVENT_UPGRADE",
        "EVENT_SELL",
        "EVENT_SET_NEW_OFF",
        "EVENT_SETJEWEL_SUCCESS_MODEL",
        "EVENT_REFRESH_UPGRADE_MODEL",
}
end

function ClassRef:onEvent(eventName, data)
    if eventName == "EVENT_HIDE_JEWEL_VIEW" then
        self:hideJewelView()
    elseif eventName == "EVENT_EQUIP_JEWEL" then
        self:equipJewel(data)
    elseif eventName == "EVENT_UNEQUIP_JEWEL" then
        self:unequipJewel(data)
    elseif eventName == "EVENT_REFRESH_BAG" then
        if data then
            self:refreshXQNode(data.euid, data.sidx)
        else
            self:refreshXQNode()
        end        
    elseif eventName == "EVENT_REFRESH_UPGRADE" then
        self:refreshSJNode()  
    elseif eventName == "EVENT_REFRESH_UPGRADEBAG" then
        self:refreshJewelBag()  
    elseif eventName == "EVENT_UPGRADE" then
        self:upgrade(data)          
    elseif eventName == "EVENT_SELL" then
        self:sellJewel(data)  
    elseif eventName == "EVENT_SET_NEW_OFF" then
        self:removeItemNewFlag()  
    elseif eventName == "EVENT_SETJEWEL_SUCCESS_MODEL" then
        self:setjewelSuccess() 
    elseif eventName == "EVENT_REFRESH_UPGRADE_MODEL" then
        self:initCacheData()
        self:refreshSJNode()
        self:changeChooseStatu()
        self._view:composeEffectCenter()
        if data then
            self:onOperate("clickJewel", data)
        end
    end
end

-- data = {
--     menuIndex =, --打开哪个页签 1（镶嵌）2（升级）3（炼金）
--     equipUid =, --选中装备uid
--     jewelUid =, --选中宝石uid
-- }
function ClassRef:openView(data)
    data = data or {}
    local menuIndex = data.menuIndex or 1

    if menuIndex == 3 and not UIHandler:isFunctionOpen(Constant.FUNC_TYPE_JEWEL_TRANSFORM) then
        display.pushToast(L("tips_1110010"))
        return
    end

    if cc.isDead(self._view) then
        self._view = JewelView.new(app.mvc.VIEWTYPE_BLUR)
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
        self._view:onOperate(handler(self, self.onOperate))
        self:addChild(self._view, data)
    end
    self._isShowInlay = self:getUDShowInlay()
    self.chooseQuality = 4
    self.equipIndex = 1
    self:initCacheData()
    self.costConfig = GD:getJewelUpCost()
    self._view:updateComposeCost(0)
    self._view:updateRedPoint(self._model:hasRedPoint())

    self.panelIdx = menuIndex
    if menuIndex == 2 then
        self:gotoComposeByJuid(data.jewelUid)
    elseif menuIndex == 3 then
        self:changeToJewelTransformPanel(data.jewelUid)
    else
        self:gotoInlayByJuid(data.equipUid, data.jewelUid)
    end

    self._view:show(menuIndex)
end

-- 1    镶嵌
-- 2    升级
-- 3    炼金
function ClassRef:onSwitchPanel(idx)
    self.panelIdx = idx
    if idx == 1 then
        self:changeToBesetPanel()
    elseif idx == 2 then
        self:changeToJewelUpPanel()
    elseif idx == 3 then
        self:changeToJewelTransformPanel()
    end
end

function ClassRef:updateRedPoint(inlay)
    if not cc.isDead(self._view) and self._model then
        self._view:updateRedPoint(self._model:hasRedPoint())
    end
end

function ClassRef:gotoComposeByJuid(juid)
    self.selectJewelUid = juid
    self:refreshSJNode()
end

function ClassRef:gotoInlayByJuid(euid, juid)
    local slotEquip
    local equipId = euid
    if juid then
        local chooseEquip = self:filtEquip(juid)
        if chooseEquip then
            equipId = chooseEquip.uid
            slotEquip = chooseEquip.slotIndex
        else
            display.pushToast(L("jewel_inlay_noequipfilt"))
        end
    end
    self:refreshXQNode(equipId,slotEquip)
end

function ClassRef:getComposeCost()
    local jewel 
    
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then
            jewel = v
            break
        end
    end

    if jewel == nil then
        return 0 
    end
    local quality = jewel:getQuality()
    local level = jewel:getLevel() 
  
    for i,v in pairs(self.costConfig) do
        -- print("$$$$$$$$$$   v.quality   ",v.quality)
        -- print("$$$$$$$$$$   v.lv   ",v.lv)
        if tonumber(v.quality) == quality and tonumber(v.lv) == level then
            local costT = string.split( v.upgradeCost, "|")
            -- print("$$$$$$$$$$   costT   ",costT[3])
            return tonumber(costT[3])

        end
    end
    return 0
end

function ClassRef:initCacheData()
    -- self.equipIndex = 1
    self.jewelIndex = 1
    self.composeChoose = {0,0,0}
    self.composePos = 1
    self.curClickJewel = nil
    self.selectJewelUid = nil
    self._curTransformJewel = nil
end

function ClassRef:closeView(data)
    if self._view then
        self:removeChild(self._view, data)
        self:clearView()
        tapm.markLevelFin()
    end
end
function ClassRef:clearView(data)
    self._view = nil

    -- 如果值不一样，存起来，只在关闭界面的时候存一次
    if self._isShowInlay ~= self:getUDShowInlay() then
        UD:saveGeneric("jewel_compose_show_inlay_status", self._isShowInlay)
    end
end
function ClassRef:removeItemNewFlag(event)
    self._model:removeItemNewFlag(event.uid)
end

-- 切换到镶嵌panel
function ClassRef:changeToBesetPanel()
    if self._view then
        self:refreshXQNode()
    end
end

-- 根据选中宝石过滤出可镶嵌装备
function ClassRef:filtEquip(jewelUid)
    -- print("··根据选中宝石过滤出可镶嵌装备·   ",jewelUid)
    local jewel = self:getJewelByUid(jewelUid)
    if jewel == nil then
        return
    end
    local equipSortByScore = nil
    local curScore = jewel:getGearScore()
    local curAttrType = jewel:getAttrType()
    local slots = {}
    local equipData=self._model:getEquipList()
    for _,equip in pairs(equipData) do
        for k,v in pairs(equip:getAllSlots()) do
            if v:fitJewel(jewel) == true then
                local slot = {}
                slot.uid = equip.uid
                slot.slotIndex = k
                slot.tid = equip.tid
                slot.lid = self._model:mapEquipLocation(equip.location)
                slot.isWera = equip:isWear()
                slot.hasJewel = false
                slot.moreScore = false
                -- slot.equip = equip
                if v.jewel then
                    slot.hasJewel = true                    
                    slot.moreScore = (curAttrType == v.jewel:getAttrType() and curScore > v.jewel:getGearScore())
                end

                table.insert(slots, slot)
            end
        end
    end

    if #slots > 1 then
        local function sortSlots(a, b)
            if a.isWera ~= b.isWera then
                return a.isWera
            elseif a.hasJewel ~= b.hasJewel then
                return a.hasJewel == false
            elseif a.moreScore ~= b.moreScore then
                return a.moreScore
            elseif a.lid ~= b.lid then
                return a.lid < b.lid
            elseif a.slotIndex ~= b.slotIndex then
                return a.slotIndex < b.slotIndex
            else
                return a.tid < b.tid
            end
        end
        table.sort(slots, sortSlots)
    end

    -- dump(slots[1].equip, "equip")
    return slots[1]
end
-- 根据选中孔位过滤出可镶嵌宝石
function ClassRef:filtJewelsCanEquiped( slot )
    if not slot then
        return
    end

    self.allJewels = self._model:getAllJewels()
    -- dump(self.allJewels, "jewels:")
    local bagJewels = {}
    for k,v in pairs( self.allJewels ) do
        if v.state == Enums.JewelState.inBag then
            table.insert( bagJewels, v )
        end
    end

    local function originSort( a, b )
        if a:getOrderLevel() == b:getOrderLevel() then
            if tonumber( a:getQuality() ) == tonumber( b:getQuality() ) then
                if a:getLevel() == b:getLevel() then
                    return a.tid > b.tid
                else
                    return a:getLevel() > b:getLevel()
                end
            else
                return tonumber( a:getQuality() ) > tonumber( b:getQuality() )
            end
        else
            return a:getOrderLevel() < b:getOrderLevel()
        end
    end
    -- 根据孔位重新排序
    -- local function sorttable( a, b )
        -- if slot:fitJewel( a ) and slot:fitJewel( b ) then -- 两者都可以镶嵌?
        --     return originSort( a, b )
        -- elseif slot:fitJewel( a ) then -- a可以镶嵌？
        --     return true
        -- elseif slot:fitJewel( b ) then -- b可以镶嵌？
        --     return false
        -- else -- 两者都不可镶嵌
        --     return originSort( a, b )
        -- end
    -- end
    local function jewsort(a, b)
        if a.type ~= b.type then
            return a.type < b.type
        elseif a:getAttrType() ~= b:getAttrType() then
            return a:getAttrType() < b:getAttrType()
        elseif a:getGearScore() ~= b:getGearScore() then
            return a:getGearScore() > b:getGearScore()
        elseif a:getLevel() ~= b:getLevel() then
            return a:getLevel() > b:getLevel()
        elseif  tonumber( a:getQuality() ) ~= tonumber( b:getQuality() ) then
            return tonumber( a:getQuality() ) > tonumber( b:getQuality() )
        else
            return a.tid > b.tid
        end
    end
    table.sort( bagJewels, jewsort)

    if self._view then
        self._view:refreshJewelBagPanel(bagJewels)

        -- 以下：更新镶嵌UI显示状态
        self.hasEquips = true
        local hasJewels = #bagJewels > 0
        self._view:refreshXQUIStatus( self.hasEquips, hasJewels )
    end
end

--刷新镶嵌界面
function ClassRef:refreshXQNode(equipUid,slotIndex)
    self.allJewels=self._model:getAllJewels()
    local bagJewels={}
    for k,v in pairs(self.allJewels) do
        if v.state==Enums.JewelState.inBag then
            table.insert(bagJewels,v)
        end
    end
    if self._view then
        local equipData=self._model:getEquipList()

        -- 以下：更新镶嵌UI显示状态
        self.hasEquips = #equipData > 0
        local hasJewels = #bagJewels > 0
        self._view:refreshXQUIStatus( self.hasEquips, hasJewels )
        if equipUid then
            for k,v in pairs(equipData) do
                if v.uid == equipUid then
                    self.equipIndex = k
                end
            end
        end

        self._view:refreshLeftList(equipData,self.equipIndex,slotIndex)
    end
end


function ClassRef:getJewelByUid( uid )
    if not uid then
        return nil
    end
    if not self.allJewels then
        self.allJewels=self._model:getAllJewels()
    end

    for k,v in pairs(self.allJewels) do
        if v:getUid() == uid then
            return v
        end
    end
    return nil
end

-- 切换到升级panel
function ClassRef:changeToJewelUpPanel()
    if self._view then
        self:initCacheData()
        self:refreshSJNode()
        self:changeChooseStatu()
        self._view:clearForUpgrade(true)
    end
end
--刷新升级界面
function ClassRef:refreshSJNode()
    -- 3蓝色4紫色
    self:refreshJewelBag()
    --根据ID计算。品质
    if self.selectJewelUid then
        local jewel = self:getJewelByUid(self.selectJewelUid)
        --宝石存在
        if jewel then
            self.chooseQuality = jewel.quality
        end
    end

    local jewels = self:getJewelByQuality(self.chooseQuality, self._isShowInlay)
    --self._view:refreshJewelTab(self.chooseQuality)
    self._view:refreshJewelList(jewels, self.selectJewelUid, self._isShowInlay)
    
end

function ClassRef:refreshJewelRenderStatus()
    local uidTab = self:convertToUidTable()
    local numt = table.nums(uidTab)
    self._view:refreshComposeBtn( ( numt>= 3))
    self._view:refreshJewelRenderStatus(uidTab)
end


--------------------- 宝石炼金 start ---------------------
-- 切换到炼金panel
function ClassRef:changeToJewelTransformPanel(jewelUid)
    self.transformJewelUid = jewelUid

    -- self:refreshJewelBag()
    if jewelUid then
        local jewel = self:getJewelByUid(jewelUid)
        --宝石存在 且没有达到最大等级。  列表不显示最大等级的宝石
        if jewel and jewel:canContinueStrength() then
            self.chooseQuality = jewel.quality
        end
    end

    local transfromPanel = self._view:getTransformPanel()
    transfromPanel:setWithEquip(self._isShowInlay)
    transfromPanel:switchJewelType(self.chooseQuality == 3 and 1 or 2)
    transfromPanel:refreshResNum()
end

-- 刷新炼金界面
function ClassRef:refreshTransformPanel()
    if cc.isDead(self._view) then return end
    if self.panelIdx ~= 3 then return end

    local transfromPanel = self._view:getTransformPanel()
    local jewels = self:getJewelByQuality(self.chooseQuality, self._isShowInlay, true)

    transfromPanel:refresh(jewels, self.transformJewelUid)

    -- 只使用一次
    self.transformJewelUid = nil
end

-- 打开宝石目标选择界面
function ClassRef:openTransformTarget(jewel)
    local jewelIds = GD:queryTransformTargetJewelIds(jewel:getClass(), jewel:getQuality(), jewel:getLevel())
    local tid = jewel:getId()
    local jewels = {}
    for i,id in ipairs(jewelIds) do
        if id ~= tid then
            jewel = Jewel.new()
            jewel:read({tid=id})
            jewels[#jewels + 1] = jewel
        end
    end

    local transfromPanel = self._view:getTransformPanel()
    transfromPanel:showTargetList(jewels)
end
--------------------- 宝石炼金 end ---------------------

function ClassRef:refreshJewelBag()
    --显示背包宝石
    -- print("刷新背包宝石  refreshJewelBag")
    --装备中卸下宝石  需要从新拉取宝石信息
    self.allJewels=self._model:getAllJewels()
    local bagJewels={}
    for k,v in pairs(self.allJewels) do
        if v.state==Enums.JewelState.inBag then
            table.insert(bagJewels,v)
        end
    end

    local function sorttable(a,b)
        if a.quality == b.quality then
            if a.lv == b.lv then
                return a.tid < b.tid
            else
                return a.lv < b.lv
            end
        else
            return a.quality < b.quality
        end
    end

    table.sort(bagJewels, sorttable)
end

-- 宝石出售
function ClassRef:sellJewel(event)
  --dump(event,"JewelController:sellJewel")
    self._model:C2S_SellJewel({event.uid})
end

-- 镶嵌珠宝成功的回调
function ClassRef:setjewelSuccess()
    if self._view and self._view:isVisible() then
        self._view:playSetJewelSuccessAni()
    end
end

-- 宝石装备
function ClassRef:equipJewel(event)
    self._model:C2S_InsertJewel(event.equipUid,event.slotIndex-1,event.jewelUid)
end

-- 宝石卸载
function ClassRef:unequipJewel(event)
    self._model:C2S_RemoveJewel(event.equipUid,event.slotIndex-1)
end

function ClassRef:hideJewelView()
    self._model:resetJewelsNewFlag()
    UIHandler:handleMessage({id = Constant.FUNC_TYPE_JEWEL,mode = "close"})
end

function ClassRef:clickLeftJewel(jewel)
    -- print("###########   clickLeftJewel")
    self.curClickJewel = jewel
    self._view:refreshBottomJewelInfo(jewel)
    local posJewel = 0
    --点击宝石 如果是已经选择的   按钮设置 “取消”。 
    if jewel then
        self._view:changeChooseBtn(not self:isRepeatClickJewel(jewel))

        local jewelUid = jewel:getUid()
        -- print("##############    jewelUid   ",jewelUid)
        self._view:refreshListClickStatus(jewelUid)
        
        for k,v in pairs(self.composeChoose) do
            if type(v) == "table" then
                if jewelUid == v:getUid() then
                    posJewel = k 
                    break
                end
            end
        end

        -- self._view:refreshBottomJewelInfo(jewel)
    end
    --点击左侧宝石，如果已选中了对应右边也要选中
    self._view:refreshRightJewelClickStatus(posJewel)
end
--获取需要 暗掉的宝石
function ClassRef:getDisableJewel()
    local disJewel = {}
    local jewelLv = -1
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then
            jewelLv = v:getLevel()
            break
        end
    end    
    local curJewelListData = self:getJewelByQuality(self.chooseQuality, self._isShowInlay)
    for k,v in pairs(curJewelListData) do
        if jewelLv >= 0 and v:getLevel() ~= jewelLv then
            local jewelUid = v:getUid()
            disJewel[jewelUid] = jewelUid
        end
    end
    return disJewel
end

function ClassRef:getShowInlay()
    return self._isShowInlay
end

function ClassRef:getUDShowInlay()
    return UD:getValueFromGenericByKey("jewel_compose_show_inlay_status") == "true"
end

function ClassRef:setShowInlay(b)
    self._isShowInlay = b
end

function ClassRef:onOperate(op, ...)
    --镶嵌
    -- print("$$$$$$$$$&&&&&&&   onOperate    ",op)
    local data = ...
    if op == "selectBtn" then
        self.equipIndex = data
        self._view:showEquipInfo(data)
        self._view:refreshSelectStatus(data)
    elseif op == "onChooseSlot" then
        self._view:onChooseSlot(data.slot,data.index)
        if data then
            self:filtJewelsCanEquiped( data.slot )
        end
    --宝石类 
    --选择右侧宝石  
    elseif op == "endActionClear" then
        self._view:clearForUpgrade(false)
    elseif op == "composeJewelClick"  then
        self._view:tipsCannotConfirmJewel(true)

    elseif op == "selectChooseJewel" then  

        local jewelDate = self.composeChoose[data]
        self:clickLeftJewel(jewelDate)
    elseif op == "refreshRender" then

        self:refreshJewelRenderStatus()
        -- local disJewel = self:getDisableJewel()
        -- print("###########    disJewel  ",#disJewel)
        -- self._view:disableJewelDark(disJewel)
    elseif op == "jewelTabChoose" then
        --self._view:refreshJewelTab(data.selectIndex)
        self.chooseQuality = data.selectIndex
        self:initCacheData()
        self._view:clearForUpgrade(true)
        self:refreshSJNode()
        self:changeChooseStatu()

        -- self._view:refreshBottomJewelInfo()
        self._view:disableJewelDark()
    elseif op == "clickJewel" then
        if data then
            self.selectJewelUid = data.uid
        end
        self:clickLeftJewel(data)
        self._view:setCanCompose(self:composeInlayed(), self:composeLvEnough())
        -- app.channelAPI:addLocalNotice("testLocalNotify",1,"测试本地推送")
    elseif op == "concelChooseJewel" then
        local posIndex = self:calculateJewelPos(self.curClickJewel)
        self._view:refreshJewelComposePanel(self.curClickJewel,posIndex,false)
        self:deleteChooseJewel(self.curClickJewel)

        self._view:changeChooseBtn(true)
        self:refreshChooseOrConcel()
    elseif op == "chooseJewelToCompose" then 
        local tipType = self:canAddChooseJewel(self.curClickJewel)
        -- 1 等级不同。2已选3个 3 已经到最大等级
        if tipType == 0 then
            local posIndex = self:calculateComposePos()
            self._view:refreshJewelComposePanel(self.curClickJewel,posIndex,true) 
            self:addChooseJewel(self.curClickJewel)
            local datatem,dataNum = self:isFullOfCompose()
            self._view:changeChooseBtn(false)
            self._view:addAniToJewel(self.curClickJewel.uid)
        else
            local str
            if tipType == 1 then
                str = L("jewel_notice02")
            elseif tipType == 2 then
                str = L("jewel_notice01")
            elseif tipType == 3 then
                str = L("jewel_notice03")
            end
            display.pushToast(str)
        end
        self:refreshChooseOrConcel()
    elseif op == "composeJewel" then
        local jewelDataTem , dataNum, jewels = self:isFullOfCompose()
        if dataNum >= 3 then
            self._model:C2S_UpgradeJewel(jewelDataTem, jewels)
        end
    elseif op == "refreshComposeJewel" then
        self:setShowInlay(data)
        self:refreshSJNode()
    ------ 下面是宝石转换的回调-----
    elseif op == "transform_jewelType" then
        --切换宝石类型
        self.chooseQuality = (data == 1) and 3 or 4
        self:refreshTransformPanel()
    elseif op == "transform_selectJewel" then
        --选中待转换的宝石
        self._curTransformJewel = data
    elseif op == "transform_withEquip" then
        --切换是否包含装备宝石
        self:setShowInlay(data)
        self:refreshTransformPanel()
    elseif op == "transform_openTarget" then
        --选中可转换的目标
        self:openTransformTarget(data)
    elseif op == "transform_confirm" then
        self:transformJewel(...)
    elseif op == "showJewelStarView" then
        self:openJewelStarView()
    end
end

function ClassRef:transformJewel(...)
    local sourceJewel, targetJewel = ...
    if sourceJewel:isInEquip() then
        local dlg = display.newConfirmDialog(L("RecastEquipedJewel"),
            function() -- 确定
                self._model:C2S_JewelTransInfo(sourceJewel, targetJewel)
            end)
        UIHandler:addPopDialog( dlg )
    else
        self._model:C2S_JewelTransInfo(sourceJewel, targetJewel)
    end
end

function ClassRef:composeInlayed()
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" and v:getOrderLevel() ~= 3 then
            return true            
        end
    end

    return false
end

function ClassRef:composeLvEnough()
    local lv = -1
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then        
            lv = v:getLevel()
            break
        end
    end

    if lv >= 0 then
        return self._model:targetJewelLvCanCompose(lv+2)
    end
    return true, 0
end

function ClassRef:isFullOfCompose()
    local jewelDataTem = {}
    local jewels = {}
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then
            jewelDataTem[i] = v:getUid()
            jewels[i] = v
        end
    end
    return jewelDataTem ,#jewelDataTem, jewels
end

function ClassRef:refreshChooseOrConcel()
    --刷新需要 暗色处理的宝石
    local disJewel = self:getDisableJewel()
    self._view:disableJewelDark(disJewel)

    local resultJewel,isAscertainJewel = self:composeResult()
    local temTab = self:convertToUidTable()
    local numt = table.nums(temTab)
    self._view:refreshComposeBtn( ( numt>= 3))
    -- dump(resultJewel)
    self._view:refreshComposeResult(resultJewel,isAscertainJewel,( numt>= 3))
    self:refreshJewelRenderStatus()
    self:changeChooseStatu()
    self._view:setCanCompose(self:composeInlayed(), self:composeLvEnough())
end
--选择改变时 刷新金币 与 特效滑块
function ClassRef:changeChooseStatu()
    local costCur = self:getComposeCost()
    self._view:updateComposeCost(costCur)
    -- self._view:updateJewelBgSlider(self.composeChoose)
end

function ClassRef:composeResult()
    local resultJewel = nil
    local isAscertainJewel = 1
    -- dump(self.composeChoose)
    for k,v in pairs(self.composeChoose) do
        if type(v) == "table" then
            -- print("所有选中宝石的ID。  ",v.tid)
            if resultJewel == nil then
                resultJewel = v
                isAscertainJewel = 2
            else
                if resultJewel.tid ~= v.tid then
                    isAscertainJewel = 1
                    break
                end
            end 
        end
    end
    return resultJewel,isAscertainJewel
end

function ClassRef:calculateComposePos()
    local index = 1
    for i,v in ipairs(self.composeChoose) do
        if type(v) ~= "table" then
            break
        end
        index = index + 1
    end

    return index
end

function ClassRef:calculateJewelPos(jewel)
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then
            if v:getUid() == jewel:getUid() then
                return i
            end
        end
    end
end
--已选中数据 到处已选中uid表
function ClassRef:convertToUidTable()
    local uidTable = {}
    for i,v in ipairs(self.composeChoose) do
       if type(v) == "table" then
        local uid = v:getUid()
        uidTable[uid] = uid
       end
    end
    return uidTable
end


function ClassRef:addChooseJewel(jewel)
    local posAdd = self:calculateComposePos()
    self.composeChoose[posAdd] = jewel
end

function ClassRef:deleteChooseJewel(jewel)
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" and v:getUid() == jewel:getUid() then
            self.composeChoose[i] = 0
            break
        end
    end
end

function ClassRef:isRepeatClickJewel(jewel)
    -- dump("检测是否重复。      ",self.composeChoose)
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" and v:getUid() == jewel:getUid() then
            return true
        end
    end
    return false
end

function ClassRef:canAddChooseJewel(jewel)
    local chooseNum = 0
    -- 0可以选中。  1 等级不同。2已选3个 3 已经到最大等级
    local tipsType = 0
    local jewelLv = jewel:getLevel()
    for i,v in ipairs(self.composeChoose) do
        if type(v) == "table" then
            if v:getLevel() ~= jewelLv then
                tipsType = 1
            end
            chooseNum = chooseNum + 1
        end
    end
    -- 优先级 等级不同  最高等级 选满3个
    if chooseNum >= 3 then
        if tipsType ~= 1 then
            tipsType = 2
        end
    end

    if not jewel:canContinueStrength() then
        if tipsType ~= 1 then
            tipsType = 3
        end
    end
    return tipsType
end

--达到最高级的宝石剔除
function ClassRef:getJewelByQuality(quality, showEquiped, isAll)
    isAll = isAll or false

    local data = {}
    local allJewel = self._model:getAllJewels()
    for i,v in ipairs(allJewel) do
        if v.quality == quality 
        and (v.state == Enums.JewelState.inBag or (v.state == Enums.JewelState.inSlot and showEquiped )) 
        and (isAll or (not isAll and v:canContinueStrength())) then
            data[#data + 1] = v
        end
    end
    local function sorttable( a, b )
        -- if a:getOrderLevel() ~= b:getOrderLevel() then
        --     return a:getOrderLevel() > b:getOrderLevel()
        if a:getLevel() ~= b:getLevel() then
            return a:getLevel() < b:getLevel()
        elseif a.type ~= b.type then
            return a.type < b.type
        elseif a:getAttrType() ~= b:getAttrType() then
            return a:getAttrType() < b:getAttrType()
        elseif  tonumber( a:getQuality() ) ~= tonumber( b:getQuality() ) then
            return tonumber( a:getQuality() ) > tonumber( b:getQuality() )
        else
            return a.tid > b.tid
        end
    end
    table.sort(data, sorttable)
    return data
end


function ClassRef:openJewelStarView()
    if cc.isDead(self._view) then return end

    local view = JewelStarView.new()
    view:onCloseView(function(sender)
        sender:removeFromParent()
    end)
    view:onOperate(function(op, params)
        if op == "showAttributePanel" then
            --跳转到属性面板
        end
    end)
    view:setName(view:getViewName())
    self._view:addChild(view)
    view:show()
end

return ClassRef
